﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStruct
{
    /// <summary>
    /// 链栈
    /// </summary>
    internal class LinkedStack
    {
        Node top;//栈顶
        int _length;//长度

        /// <summary>
        /// 入栈
        /// </summary>
        /// <param name="data"></param>
        public void Push(int data)
        {
            Node newNode = new Node(data);
            if (top == null)
            {
                top = newNode;
            }
            else
            {
                newNode.Next = top;
                top = newNode;
            }
            _length++;
        }

        /// <summary>
        /// 出栈
        /// </summary>
        /// <returns></returns>
        public Node Pop()
        {
            if (top == null)
            {
                return null;
            }

            Node node = top;
            top = top.Next;
            _length--;
            return node;
        }

        /// <summary>
        /// 是否为空栈
        /// </summary>
        /// <returns></returns>
        public bool IsEmpty()
        {
            return top == null;
        }

        /// <summary>
        /// 打印栈中的所有元素
        /// </summary>
        public void Print()
        {
            Node currentNode = top;
            while (currentNode != null)
            {
                Console.Write($"{currentNode.Data} ");
                currentNode = currentNode.Next;
            }

            Console.WriteLine($"栈顶:{top?.Data} 堆栈长度:{GetLength()}");
        }

        public int GetLength()
        {
            return _length;
        }

        /// <summary>
        /// 获取栈顶元素 只返回栈顶元素，不出栈
        /// </summary>
        /// <returns></returns>
        public Node Peek()
        {
            if (top == null)
            {
                throw new Exception("空栈！");
            }
            return top;
        }
    }
}
